<template>
    <div class="boxOne">
        <div class="setBox">
            <!--  -->
            <span class="Title" style="margin-top:10px">设置</span>
            <div class="ddBox">
                <div class="ddOne">
                    <span style="flex-shrink: 0;margin-right:10px;line-height:47px">壁纸</span>
                    <div class="pathBox"><span class="mspan">{{filePath}}</span></div>
                    <button type="button" class="butA" @click="fileDeing">选择</button>
                    <button type="button" class="butA c-red" @click="QK">清空</button>
                </div>

            </div>
            <!--  -->
            <span class="Title">SD设置</span>
            <div class="XZ">
                <div class="XZB">
                    <span class="XZT">生成GPU:</span>
                    <Select v-model="GPUl" :title="GPUl" style="width:200px;height:30px;background-color: #ffffff50;line-height:30px;font-size:12px;overflow: hidden;">
                        <Option v-for="item in lb" :value="item.value" :key="item.value">{{ item.label }}</Option>
                    </Select>
                </div>
                <div class="XZB">
                    <span class="XZT">显存优化:</span>
                    <Select v-model="XCO" style="width:200px;height:30px;background-color: #ffffff50;line-height:30px;">
                        <Option v-for="item in XCYH" :value="item.value" :key="item.value">{{ item.label }}</Option>
                    </Select>
                </div>
                <div class="XZB">
                    <span class="XZT">启动端口:</span>
                    <input type="text" class="Input" v-model="DK">
                </div>
                <div class="XZB">
                    <span class="XZT">速度优化:</span>
                    <Select v-model="SDO" style="width:200px;height:30px;background-color: #ffffff50;line-height:30px;">
                        <Option v-for="item in YH" :value="item.value" :key="item.value">{{ item.label }}</Option>
                    </Select>
                </div>
            </div>
            <div class="XZs">
                <div class="XZB">
                    <Checkbox  v-model="auto" ></Checkbox >
                    <span class="XZT">启动完成自动打开浏览器</span>
                </div>
                <div style="width:140px"></div>
                <div class="XZB">
                    <Checkbox  v-model="noHalf"></Checkbox >
                    <span class="XZT">不使用半精度模型</span>
                </div>
                <div class="XZB">
                    <Checkbox  v-model="noHalfAve"></Checkbox >
                    <span class="XZT">不使用半精度VAE</span>
                </div>
                <div style="width:187px"></div>
                <div class="XZB">
                    <Checkbox  v-model="disNAN"></Checkbox >
                    <span class="XZT">关闭数值溢出检查</span>
                </div>
            </div>
            <span>常见问题详解(选中后ctrl+c可以复制)</span><br>
            <span>手部问题：<span style="user-select: all;">https://www.bilibili.com/read/cv23421417/</span></span><br>
            <span>模型下载：<span style="user-select: all;">https://www.liblibai.com/</span></span><br>
            <span>运行报错：<span>百度一下</span></span><br>
            <!--  -->
            <!-- <span class="Title" style="margin-top:10px">DD设置</span> -->
            <div class="ddBox">
                <!-- <div class="ddOne">
                    <span style="flex-shrink: 0;margin-right:10px">特别关注</span>
                    <textarea v-model="roomL" class="inputs" name="" id="" cols="30" rows="4" placeholder="输入你的想订阅的主播房间号，用英文逗号分隔（目前只支持B站）"></textarea>
                </div>
                <span>特别关注：指你希望能在列表里的主播开播时能第一时间弹窗通知你的设置</span> -->
            </div>
            
        </div>
        <!--  -->
            <div class="bBox">
                <button type="button" class="butMY" @click="react">恢复默认设置</button>
                <button type="button" class="butMY" >打开命令提示符</button>
                <button type="button" class="butMY" @click="save">一键保存</button>
                <button type="button" class="butMY yp">原神 启动</button>
            </div>
    </div>
    
</template>

<script setup>
import { ref,onMounted } from "vue";
import { Select,Option,Checkbox } from "view-ui-plus";
const fs = require('fs')
// import 'view-ui-plus/dist/styles/viewuiplus.css'
const { ipcRenderer } = require('electron')
import { storeToRefs } from 'pinia'
import useNoiseStatistics from '../stores/index';

const {resolve} = require('path')
//获取pinia
const counterStore = useNoiseStatistics()
const { SDPath,appBZ,sessdata,XC,outGS,roomLists,likeRoomList,likeRB } = storeToRefs(counterStore)

var canvas = document.createElement('canvas');
var gl = canvas.getContext('webgl');  // 等同于 canvas.getContext('experimental-webgl');
var debugInfo = gl.getExtension('WEBGL_debug_renderer_info');


const filePath = ref('无')
// 端口
const DK = ref('7860')
const lb = ref([])
//
const XCO = ref('medvram')
//
const SDO = ref('xFormers')
const XCYH = ref([
    {value: 'height',label: '高显存(12GB及以上)'},
    {value: 'medvram',label: '中显存(6GB至10GB)'},
    {value: 'lowvram',label: '低显存(4GB及以下)'},
])
// 优化选项
const YH = ref([
    {value: '无',label: '无'},
    {value: 'xFormers',label: '使用xFormers(推荐)'},
])
// 单选
const auto = ref(true)
const noHalf = ref(false)
const noHalfAve = ref(false)
const disNAN = ref(false)
const roomL = ref(likeRB)

//gpu列表
// const GPUl = ref([])
const GPUl = ref()

const pathOne = ref(SDPath)
//读取启动配置
const startJSON = ref([])
//详细参数配置
const moreSet = ref([])
const moreSets = ref([])
const moreSetOne = ref([])
const echo = ref('')
onMounted(()=>{
    openBat()
    gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL).split(',').forEach(ele => {
        if(ele.slice(1,15) == 'NVIDIA GeForce'){
            lb.value.push({value: ele,label: ele})
        }
    });
    GPUl.value = lb.value[0].value

    
    ipcRenderer.on('openFliePathE', (event, message) =>{
        if (message.filePaths[0] == undefined) {
        }else{
            counterStore.appBZ = message.filePaths[0]
            let content = JSON.stringify({ses:counterStore.sessdata,appbz:counterStore.appBZ,xc:counterStore.XC,gs:counterStore.outGS,room:{likeR:counterStore.likeRB,RL:counterStore.roomLists,likerb:counterStore.likeRB}})
            fs.writeFile(counterStore.SDPath+'\\LiveImg\\Config.txt',content,(err)=>{
                if(err) {
                        console.error(err);
                        return
                }
                filePath.value = message.filePaths[0]
                document.documentElement.setAttribute('theme', 'light')
            });
            
        }
        
    })

    if(counterStore.appBZ != '' && counterStore.appBZ != '无'){
        filePath.value = counterStore.appBZ
    }

})
//打开文件对话框
function fileDeing() {
    ipcRenderer.send('openFliePathS')
}
//清空路径
function QK() {
    filePath.value = '无'
    counterStore.appBZ = '无'
    document.documentElement.removeAttribute('theme')
}

//读取配置
function openBat() {
    fs.readFile(counterStore.SDPath+'\\SD\\webui-user.bat', { encoding: "utf-8" }, (err, result) => {
    if (err) {
      console.log(err, "读取文件内容失败");
    } else {
    //   console.log(result);
    //   console.log(result.split('\n')[5].split('--'))
      startJSON.value = result.split('\n')
      for (let index = 0; index < startJSON.value.length; index++) {
            const element = startJSON.value[index];
            if (index == 5) {
                moreSets.value = element.split('--')
                for (let index = 0; index < moreSets.value.length; index++) {
                    const ele = moreSets.value[index];
                    if(ele == 'no-half'){
                        noHalf.value = true
                    }
                    if(ele == 'no-half-vae'){
                        noHalfAve.value = true
                    }
                    if(ele == '--disable-nan-check'){
                        disNAN.value = true
                    }
                    if (ele.split('=')[0] == 'prot') {
                        DK.value = ele.split('=')[1]
                    }
                    if (ele == 'xformers') {
                        SDO.value = 'xFormers'
                    }
                    // if (ele != 'height') {
                    //     XCO.value = 'height'
                    // }
                    // if (ele == 'xformers') {
                    //     SDO.value = 'xFormers'
                    // }
                }
            }
        }
    }
    
  });
}

function setJSON() {
    moreSet.value = []
    moreSetOne.value = []
    if (noHalf.value) {
        moreSet.value.push('--no-half')
    }
    if (noHalfAve.value) {
        moreSet.value.push('--no-half-vae')
    }
    if (disNAN.value) {
        moreSet.value.push('--disable-nan-check')
    }
    // if (auto.value) {
    //     moreSet.value.push('--autolaunch')
    // }
    /**
     * 其他参数
     */
    if (SDO.value == 'xFormers') {
        moreSet.value.push('--xformers')
    }
    if (DK.value != null && DK.value != undefined && DK.value != '') {
        moreSet.value.push('--port='+DK.value)
    }
    if (XCO.value != '' &&XCO.value != null && XCO.value != undefined) {
        if (XCO.value != 'height') {
            moreSet.value.push('--'+XCO.value)
        }
    }

    for (let index = 0; index < moreSet.value.length; index++) {
        const element = moreSet.value[index];
        if (index >=0) {
            moreSetOne.value = moreSetOne.value+element+' '
        }else if(index == moreSet.value.length){
            moreSetOne.value = moreSetOne.value+element
        }
    }
    
    ZH(moreSetOne.value)
}

function ZH(par) {
    echo.value = ''
    for (let index = 0; index < startJSON.value.length; index++) {
        if (index == 5) {

            startJSON.value.splice(5, 1, moreSets.value[0].split('\r')[0]+par);
        }
        echo.value = echo.value+startJSON.value[index]+'\n'
    }
    // console.log(echo.value)
}

//写入配置
function save() {
    setJSON()
    writd()
    let content = JSON.stringify({ses:counterStore.sessdata,appbz:counterStore.appBZ,xc:counterStore.XC,gs:counterStore.outGS,room:{likeR:counterStore.likeRB,RL:counterStore.roomLists,likerb:counterStore.likeRB}})
    fs.writeFile(counterStore.SDPath+'\\LiveImg\\Config.txt',content,(err)=>{
        if(err) {
                console.error(err);
                return
        }
    });
}

//写入
function writd() {
    // console.log(echo.value)
    fs.writeFile(counterStore.SDPath+'\\SD\\webui-user.bat',echo.value,err => {
    //如果写入失败，则回调函数调用时，会传入错误对象，如写入成功，会传入 null
        if (err) {
            console.log(err);
            return;
        }
    // console.log("写入成功");
    })
}

//回复默认配置
function react() {
    moreSetOne.value = []
    ZH(moreSetOne.value+'--xformers')
    writd()
}
</script>

<style scoped>
.mspan{
    width: 470px;
	overflow: hidden; /*超出部分隐藏*/
	text-overflow: ellipsis; /*超出部分省略号表示*/
	white-space: nowrap; /*强制单行显示*/
	display: inline-block; /*转换为行内块元素*/
}
.pathBox{
    width: 100%;
    display: flex;
    background-color: var(--def-box-color);
    backdrop-filter: blur(var(--def-filler));
    margin-top: 5px;
    max-height: 36px;
    /* padding: 5px 15px; */
    user-select: auto !important;
    flex-wrap: wrap;
    align-content: center;
    padding-left: 10px;
}
.ddOne{
    display: flex;
    margin-top: 10px;
}
.boxOne{
    height: 450px;
}
.bBox{
    display: flex;
    justify-content: center;
}
.butMY{
    border: none;
    outline: none;
    background-color: var(--def-button-color-blue);
    backdrop-filter: blur(var(--def-filler));
    color: #ffffff81;
    margin: 5px 15px;
    padding: 10px 20px;
    border-radius: 1px;
    font-family: myFont;
    cursor: pointer;
}
.butA{
    border: none;
    outline: none;
    background-color: var(--def-button-color-blue);
    backdrop-filter: blur(var(--def-filler));
    color: #fff;
    margin: 5px;
    padding: 10px 20px;
    border-radius: 1px;
    font-family: myFont;
    cursor: pointer;
    flex-shrink: 0;
}
.c-red{
    background-color: var(--def-button-color-red) !important;
}
.butMY:hover{
    color:#fff;
}
.inputs{
    border-radius: 2px;
    background-color: var(--def-box-color);
    backdrop-filter: blur(var(--def-filler));
    color: #fff;
    font-family: myFont;
    font-size: 16px;
    padding: 10px 15px;
    outline: none;
    border: none;
    width: 100%;
    margin-bottom: 10px;
    resize: none;
}
.yp{
    background-color: var(--def-button-color-pink);
}
.ivu-radio {
    display: inline-block;
    margin-right: 4px;
    white-space: nowrap;
    position: relative;
    line-height: 1;
    vertical-align: middle;
    cursor: pointer;
}
.ivu-radio-inner {
    display: inline-block;
    width: 16px;
    height: 16px;
    position: relative;
    top: 0;
    left: 0;
    background-color: #fff;
    border: 1px solid #dcdee2;
    border-radius: 50%;
    transition: all .2s ease-in-out;
}
.ivu-radio-input {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 1;
    opacity: 0;
    cursor: pointer;
}
.ivu-radio-checked .ivu-radio-inner {
    border-color: #2d8cf0;
}


.Input{
    border: none;
    background-color: #ffffff50;
    /* backdrop-filter: blur(var(--def-filler)); */
    color: #fff;
    font-family: myFont;
    font-size: 16px;
    padding: 5px 10px;
    outline: none;
}
:depp(.ivu-select,.ivu-select-single,.ivu-select-default){
    overflow: hidden;
    border-top-left-radius: 2px;
    border-top-right-radius: 2px;
}
:deep(.ivu-select-item:hover){
    background-color: #fff;
    color: #000;
}
:deep(.ivu-select-item){
    padding: 0 10px;
    background-color: var(--def-box-color);
    backdrop-filter: blur(var(--def-filler));
}
:deep(.ivu-select-selection){
    padding-left: 10px;
    max-height: 30px;
}
:deep(.ivu-select-dropdown-list){
    list-style: none;
    padding: 0;
    margin: 0;
    overflow: hidden;
    border-bottom-left-radius: 2px;
    border-bottom-right-radius: 2px;
}
:deep(.ivu-select-dropdown){
    background-color:#ffffff63;
    backdrop-filter: blur(10px);
    margin: 0;
    overflow: hidden;
    border-bottom-left-radius: 2px;
    border-bottom-right-radius: 2px;
}
.XZT{
    display: flex;
    flex-wrap: wrap;
    align-content: center;
    margin-right: 10px;
}
.XZB{
    display: flex;
    margin: 10px 15px;
}
.XZ{
    display: flex;
    padding-top: 10px;
    padding-left: 30px;
    justify-content: center;
    flex-wrap: wrap;
}
.XZs{
    display: flex;
    padding-top: 10px;
    padding-left: 50px;
    justify-content: flex-start;
    flex-wrap: wrap;
}
.setBox{
    padding: 5px 20px;
    color: #fff;
    overflow-y: auto;
    height: 360px;
}
.Title{
    font-size: 25px;
    color: #fff;
}

/*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/
.setBox::-webkit-scrollbar,.LiveList::-webkit-scrollbar  {
    width: 6px;
    height: 6px;
    /* background-color:pink; */
}
/*定义滚动条轨道*/
.setBox::-webkit-scrollbar-track,.LiveList::-webkit-scrollbar-track {
    background-color: transparent;
    -webkit-border-radius: 0;
    -moz-border-radius: 0;
    border-radius: 0
}
/*定义滑块 内阴影+圆角*/
.setBox::-webkit-scrollbar-thumb,.LiveList::-webkit-scrollbar-thumb {
    background-color: #30B07F00;
    background-image: -webkit-linear-gradient(45deg,rgba(255,255,255,0) 100%,transparent 100%,transparent 50%,rgba(255,255,255,0) 50%,rgba(255,255,255,0) 75%,transparent 75%,transparent);
    -webkit-border-radius: 0;
    -moz-border-radius: 0;
    border-radius: 0;
    background-color:rgb(52, 116, 255);
}

input::-webkit-input-placeholder {
    /* placeholder颜色  */
    color: var(--def-placeholder);
}
textarea::-webkit-input-placeholder {
    /* WebKit browsers */
    /* placeholder颜色  */
    color: var(--def-placeholder);
}
</style>